package com.company.design.construct.flyweight;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * @author yingfing
 * @create 2020--09--26 9:31
 * @describe
 */
public class ConnectionPool {
    private String url = "http://localhost:3306/test";
    private String username = "root";
    private String password = "root";
    private String driverClass = "com.mysql.jdbc.Driver";

    private int poolSize = 100;
    private Vector<Connection> pool;
    private Connection connection = null;

    public ConnectionPool() {
        pool = new Vector<>(poolSize);

        for (int i = 0; i < poolSize; i++) {
            try {
                Class.forName(driverClass);
                connection = DriverManager.getConnection(url, username, password);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Connection getConnection() {
        if (poolSize > 0) {
            Connection connection = pool.get(0);
            pool.remove(connection);
            return connection;
        }
        return null;
    }

    public synchronized void release() {
        pool.add(connection);
    }
}
